package com.aoxun.android.commons.base;
/**
 * Created by Onelong on 2017/11/20.
 */
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.IdRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.socks.library.KLog;
import com.aoxun.android.commons.ICreateCallback;
import com.aoxun.android.commons.IMessageHandler;
import com.aoxun.android.commons.impl.BaseFragmentMessageHandler;
import com.aoxun.android.commons.impl.BaseUiDelegate;
import com.trello.rxlifecycle2.components.support.RxFragment;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


public abstract class BaseFragment extends RxFragment implements ICreateCallback {
	//用于组件直接通信
	private IMessageHandler baseFragmentMessageHandler;
	private String TAG;
	//为将来注入
	public BaseUiDelegate uiDelegate;

	protected BaseActivity activity;
	private View rootView;

	protected LayoutInflater inflater;

	protected boolean hasLoad;//只加载一次
	protected boolean hasPrepared;//

	private Disposable mDisposable;

	protected final Consumer<Object> loadingShowAction = new Consumer<Object>() {
		@Override
		public void accept(@NonNull Object o) throws Exception {
			KLog.d("start event------>");
			Observable.just(1)//.delay(200, TimeUnit.MILLISECONDS) //延时200毫秒
					.observeOn(AndroidSchedulers.mainThread())
					.doOnDispose(new Action() {
						@Override
						public void run() throws Exception {
							getUiDelegate().dismissLoadingDlg();
						}
					})
					.subscribe(new Observer<Integer>() {
						@Override
						public void onSubscribe(@NonNull Disposable disposable) {
							mDisposable = disposable;
						}
						@Override
						public void onNext(@NonNull Integer integer) {
							getUiDelegate().showLoadingDlg();
						}
						@Override
						public void onError(@NonNull Throwable throwable) {}
						@Override
						public void onComplete() {}
					});
		}
	};

	protected final Action loadingHideAction = new Action() {
		@Override
		public void run() throws Exception {
			KLog.d("end event<------");
			if (!mDisposable.isDisposed()) {
				mDisposable.dispose();
			}
			getUiDelegate().dismissLoadingDlg();
		}
	};

	/**
	 * @param title
	 */
	public void setTitle(CharSequence title) {
		if(activity!=null){
			activity.setTitle(title);
		}
	}

	/**
	 * @param resid
	 */
	public void setTitle(int resid) {
		if(activity!=null){
			activity.setTitle(resid);
		}
	}

	public BaseUiDelegate getUiDelegate() {
		if (uiDelegate == null) {
			if(activity == null){
				activity = (BaseActivity) getActivity();
			}
			uiDelegate = BaseUiDelegate.create(activity);
		}
		return uiDelegate;

	}

	protected void onInvisible() {
	}

	protected void onVisible() {
		if (hasPrepared && !hasLoad) {
			hasLoad = true;
			lazyLoad();
		}
	}

	/**
	 * 子Activity 实现该方法 处理主线程UI
	 *
	 * @param msg
	 */
	public abstract void handleMessage(Message msg);
	protected void lazyLoad(){}


	/**
	 * @param inflater
	 * @param container
	 * @param savedInstanceState
	 * @return
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		ImmersionBar.with(this).init();
		this.inflater = inflater;
		rootView = inflater.inflate(getLayoutId(), container, false);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if(getActivity() instanceof BaseActivity)
			activity = (BaseActivity) getActivity();
		else {
			throw new RuntimeException("不是BaseActivity的实例");
		}

		getUiDelegate();
		TAG = getClass().getSimpleName();
		if(baseFragmentMessageHandler==null)
			baseFragmentMessageHandler = new BaseFragmentMessageHandler(this);

		initView();
		setListener();
		initData(savedInstanceState);

		hasPrepared = true;
		if (getUserVisibleHint()) {//防止页面在不可见时加载
			onVisible();//第一个页面在执行onActivityCreated前就已调用setUserVisibleHint,对用户可见getUserVisibleHint=true,
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (getUserVisibleHint()) {
			onVisible();
		} else {
			onInvisible();
		}
	}

	@Override
	public void onDestroy() {
		/*
		if (uiDelegate != null) {
			uiDelegate.destory();
		}
*/
		if(baseFragmentMessageHandler!=null){
			baseFragmentMessageHandler.destory();
		}

		uiDelegate = null;
		rootView = null;
		activity = null;
		baseFragmentMessageHandler = null;
		super.onDestroy();
		//System.gc();
//		ImmersionBar.with(this).destroy();
	}


	public IMessageHandler getMessageHandler(){
		return baseFragmentMessageHandler;
	}
	//public IMessageHandler getActivityMessageHandler(){
	//	return activity.getMessageHandler();
	//}

	public <T extends View> T find(@IdRes int id) {
		return (T)rootView.findViewById(id);
	}

	/**
	 * 获取文本框的文本
	 * 
	 * @param e
	 * @return
	 */
	public String getEditTextString(EditText e) {
		String str;
		str = (e == null ? "" : e.getText().toString().trim());
		return str;
	}



	/**
	 * 检测文本编辑器是否有输入内容
	 * 
	 * @param et
	 * @return true代表没有输入内容
	 */
	public boolean checkEditContentIsNull(EditText et) {
		if (et == null) {
			return true;
		} else {
			if (!getEditTextString(et).trim().equals("")) {
				return false;
			}
		}
		return true;
	}

}
